package cn.fl.risknew.controller;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.inscare.service.IInsPayInfoService;
import cn.fl.mcr.condition.McrBillDQC;
import cn.fl.mcr.service.IMcrBillDService;
import cn.fl.mcr.vo.McrBillDVO;
import cn.fl.overdue.condition.*;
import cn.fl.overdue.dto.OverdueCstDTO;
import cn.fl.overdue.service.IOverdueApiService;
import cn.fl.payschd.condition.PaySchDQueryCondition;
import cn.fl.project.api.IPrjPrdDtlExtApiService;
import cn.fl.project.condition.PrjFileInfoQueryCondition;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.condition.PrjPrdPaySchDQueryCondition;
import cn.fl.project.constant.PrjFileInfoConstant;
import cn.fl.project.dto.PrjPrdDtlExtDTO;
import cn.fl.project.service.*;
import cn.fl.project.vo.*;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.risknew.service.IOverdueCalculatorApiService;
import cn.fl.risknew.service.IRiskLevelService;
import cn.fl.risknew.service.IRiskOverdueService;
import cn.fl.risknew.service.IRskUlFileLogService;
import cn.fl.risknew.vo.*;
import cn.fl.system.api.ISysSequenceApiService;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.flow.facade.flow.api.IFlowApiService;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import ins.car.facade.car.car.common.MoneyConvert;
import ins.car.facade.car.car.condition.InsPayDetailIns03QC;
import ins.car.facade.car.car.dto.InsPayDetailIns03DTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 新版逾期催收
 * 逾期催收重构
 * 逾期催收页面的请求
 * 作者:hongyanbo
 * 时间:2018/8/20
 */
@RequestMapping("/risk/overdueCollect")
@Controller
public class RiskOverdueCollectController {
	private static final Logger logger = LoggerFactory.getLogger(RiskOverdueCollectController.class);
	/**
     * 客户 服务层BEAN
     */
    @Autowired
    private ICstBscInfoService cstBscInfoService;
    @Autowired
    private IPrjBscInfoService prjBscInfoService;//项目基础信息表
    @Autowired
    private IRiskOverdueService overdueService;
    @Autowired
    private IOverdueCalculatorApiService overdueCalculatorApiService;
    @Autowired
    private IOverdueApiService iOverdueApiService;
    /**
     * 项目产品明细
     */
    @Autowired
    private IPrjPrdDtlService dtlService;
    /**
     * 合格证
     */
    @Autowired
    private IPrjPrdVehInfoService vehInfoService;
    /**
     * 上牌
     */
    @Autowired
    private IPrjPrdLicInfoService licInfoService;
    /**
     * 抵押
     */
    @Autowired
    private IPrjPrdMtgService mtgService;
    @Autowired
    private IPrjPrdDtlExtApiService dtlExtApiService;
    @Autowired
    private IPrjPrdPaySchMService prjPrdPaySchMService;

    /**
     * 支付表明细服务层
     */
    @Autowired
    private IPrjPrdPaySchDService prjPrdPaySchDService;

    @Autowired
    private IPrjFileInfoService prjFileInfoService;

    @Autowired
    private IRskUlFileLogService iRskUlFileLogService;

    @Autowired
    private IFlowApiService iFlowApiService;

    @Autowired
    private ISysSequenceApiService sysSequenceApiService;

    @Resource
    private IRiskLevelService riskLevelService;

    /**
     * 到资料补充页面前check是否有正在审核的
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/checkCount.do",  method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public DataResultVO checkCount(HttpServletRequest request, HttpServletResponse response) {
        DataResultVO dataResultVO = new DataResultVO();
        dataResultVO.setSuccess(BaseConstant.IS_YESNO_YES);
        String prjId = request.getParameter("prjId");//项目ID
        int i = iOverdueApiService.searchRskFileFlowCheckingCount(Long.valueOf(prjId));
        dataResultVO.setData(i);
        if(i>0){
            dataResultVO.setInfo("此项目存在正在审核的补充资料，暂时不能发起此流程！");
            dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            dataResultVO.setData(i);
            return dataResultVO;
        }
        return dataResultVO;
    }
    /**
     * 到资料补充页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toSupplement.do",  method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toSupplement(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toSupplementPage", "加载到贷后资料补充页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = null;
        mav = new ModelAndView("/risknew/ovdueCollect/supplement");
        String prjId = request.getParameter("prjId");//项目ID
        mav.addObject("prjId", prjId);
        mav.addObject("cfgCd", PrjFileInfoConstant.CODE_UL_PRJ_FILE_CFG_CD);
        if(StringUtils.isNotEmpty(prjId)){
            PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjId));
            if(null!=prjBscInfoVO){
                mav.addObject("cstId", prjBscInfoVO.getCstId());
                mav.addObject("cstMgrOrgCd", prjBscInfoVO.getCstMgrOrgCd());//客户经理组织架构代码
                mav.addObject("prjTypCd", prjBscInfoVO.getPrjTypCd());//项目类型
                mav.addObject("buOrgCd", prjBscInfoVO.getBuOrgCd());//所属事业部
                mav.addObject("insCode", StringUtils.isNotEmpty(prjBscInfoVO.getInsCode())?prjBscInfoVO.getInsCode():"");//机构编码
            }
        }
        String ctrlKey = request.getParameter("ctrlKey");//控制键 1.可上传、删除 2.可验证 3.不可操作
        if(StringUtils.isEmpty(ctrlKey)){//没有控制键
                ctrlKey = "3";
        }
        if("2".equals(ctrlKey)||"3".equals(ctrlKey)){
            //查询最新一条补充说明
            RskUlFileLogVO rskUlFileLogVO = iRskUlFileLogService.selectLastByPrjId(Long.valueOf(prjId));
            if(null != rskUlFileLogVO){
                mav.addObject("UlRem",rskUlFileLogVO.getUlRem());
            }
        }
        //获取id
        Long rskFileId = sysSequenceApiService.getFun("FN_GEN_RSK_UL_FILE_LOG_ID");
        mav.addObject("rskFileId",rskFileId);
        mav.addObject("ctrlKey", ctrlKey);
        return mav;
    }

    /**
     * 初始化资料补充列表
     */
    @RequestMapping(value = "/initSupplementList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initPrjFileInfoList(HttpServletRequest request, HttpServletResponse response) {
        String rskFileId = request.getParameter("rskFileId");//ID
        String cfgDtlCd = request.getParameter("cfgDtlCd");//子配置编号
        String cstMgrOrgCd = request.getParameter("cstMgrOrgCd");//客户经理组织架构
        String prjTypCd = request.getParameter("prjTypCd");//项目类型
        PrjFileInfoQueryCondition qc = new PrjFileInfoQueryCondition();
        if(StringUtils.isNotBlank(rskFileId)){
            qc.setPrjId(Long.valueOf(rskFileId));
        }
        if(StringUtils.isNotEmpty(cfgDtlCd)){
            qc.setCfgDtlCd(cfgDtlCd);
        }
        if(StringUtils.isNotEmpty(cstMgrOrgCd)){
            qc.setCstMgrOrgCd(cstMgrOrgCd);
        }
        if(StringUtils.isNotBlank(prjTypCd)){
            qc.setPrjTypCd(prjTypCd);
        }
        BaseLogUtils.info(logger, "initPrjFileInfoList", "初始化贷后资料补充列表.DATA:" + JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName());
        List<PrjFileInfoVO> list = this.prjFileInfoService.searchPrjSupplementInfoList(qc);
        if (CollectionUtils.isNotEmpty(list)) {
            return new ListPageVO<PrjFileInfoVO>(list, list.size());
        }
        return new ListPageVO<PrjFileInfoVO>(new ArrayList<PrjFileInfoVO>(), 0);
    }

    /**
     * 提交审核
     */
    @RequestMapping(value = "/saveFlow.do", method = { RequestMethod.POST,RequestMethod.GET })
    @ResponseBody
    public Object saveFlow(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String buOrgCd = request.getParameter("buOrgCd");
        String rskFileId = request.getParameter("rskFileId");
        String UlRem = request.getParameter("UlRem");
        String prjId = request.getParameter("prjId");
        String currentOrgCd = CurrentThreadContext.getCurrentOrgCd();

        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "发起成功");
        if(StringUtils.isEmpty(rskFileId)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "saveFlow", "提交审核,主键不存在.[id="+rskFileId+"]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        try {
            //发起流程
//             cn.fl.risknew.service.IRiskOverdueService#getFlowStartParamsDTO 这个是获取发起流程的参数
//             fl.flow.facade.flow.api.IFlowApiService#noTransFlowStart  这个是发起流程的接口
            FlowStartParamsDTO flowStartParamsDTO = overdueService.getFlowStartParamsDTO(currentOrgCd,buOrgCd,"FS01",Long.valueOf(rskFileId),"RSK_UL_FILE_LOG");
            DataResultDTO dataResultDTO = iFlowApiService.noTransFlowStart(flowStartParamsDTO);
            //添加记录
            RskUlFileLogVO rskUlFileLogVo = new RskUlFileLogVO();
            rskUlFileLogVo.setId(Long.valueOf(rskFileId));
            rskUlFileLogVo.setUlRem(UlRem);
            rskUlFileLogVo.setPrjId(Long.valueOf(prjId));
            Integer integer = iRskUlFileLogService.addNew(rskUlFileLogVo);

            BaseLogUtils.info(logger, "saveFlow", "发起流程成功.[id="+rskFileId+"] DATA:" + JSONObject.toJSONString(dataResultDTO), CurrentThreadContext.getCurrentUserName());
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "saveFlow", "发起流程失败.[id="+rskFileId+"] DATA:"  + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "saveFlow", "发起流程失败.[id="+rskFileId+"] DATA:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 小贷账单明细服务层
     */
    @Autowired
    private IMcrBillDService mcrBillDService;

    /**
     * 保险支付服务层
     */
    @Autowired
    private IInsPayInfoService insPayInfoService;

    /**
     * 逾期催收tab父页面
     * @return
     */
    @RequestMapping("/toOverdueIndex.do")
    public ModelAndView toOverdueIndex(ModelAndView model){
        model.setViewName("/risknew/ovdueCollect/overdueCollect");
        return model;
    }

    /**
     * 逾期任务TAB页
     * @param model
     * @return
     */
    @RequestMapping("/toOverdueTaskList.do")
    public ModelAndView toOverdueTaskList(ModelAndView model){
        // 事业部
        List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
        model.addObject("buOrgCdList", JSON.toJSONString(orgList));
        //查询项目类型
        List<KeyValueVO> projectTypeList = this.prjBscInfoService.getPrjTypCdALLKV();
        model.addObject("projectTypeList", projectTypeList);
        model.setViewName("/risknew/ovdueCollect/capOverdueInfoList");

        // 逾期催收和我的任务公用一个JSP 用这个变量来区分列表查询
        model.addObject("view","overdueTaskList");

        //查询第三方机构
        List<FriBaseInfoVO> list = this.overdueService.getFriBaseInfoList();
        model.addObject("friBaseList", list);

        // 所属区域
        List<KeyValueVO> regionList = this.prjBscInfoService.getRegionList();
        model.addObject("regionList", regionList);
        // 业务类型
        List<KeyValueVO> bizTypeList = this.prjBscInfoService.getBizTypeList();
        model.addObject("bizTypeList",bizTypeList);

        return model;
    }

    /**
     * 组任务
     * @param model
     * @return
     */
    @RequestMapping("/toGroupTaskListPage.do")
    public ModelAndView toGroupTaskListPage(ModelAndView model){
        model.setViewName("/risknew/ovdueCollect/groupTaskList");
        // 事业部
        List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
        model.addObject("buOrgCdList", JSON.toJSONString(orgList));
        model.addObject("queryType","2"); //TODO
        List<KeyValueVO> insList = this.overdueService.getInsCdKeyValueList();
        model.addObject("insList",JSON.toJSONString(insList));

        return model;
    }

    /**
     * 组任务  分页数据
     */
    @ResponseBody
    @RequestMapping("/initGroupTask.do")
    public ListPageVO initGroupTask(OverdueBaseCondition condition,int page ,int pagesize){
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
		String insCode = condition.getInsCode();
		if(StringUtils.isNotBlank(insCode)){
			List<String> insCodeList = Arrays.asList(insCode.split(";"));
			condition.setInsCode(null);
			condition.setInsCodeList(insCodeList);
		}
		String buOrgCd = condition.getBuOrgCd();
		if(StringUtils.isNotBlank(buOrgCd)){
			List<String> buOrgCdList = Arrays.asList(buOrgCd.split(";"));
			condition.setBuOrgCd(null);
			condition.setBuOrgCdList(buOrgCdList);
		}
		Pager pager = this.overdueService.selectGroupTaskListPage(condition, page, pagesize);
        return new ListPageVO(pager.getResultList(),pager.getTotalCount());
    }
    /**
     * 获取逾期用户信息
     * @return
     */
    @ResponseBody
    @RequestMapping("/overdueCustomerListPage.do")
    public ListPageVO overdueCustomerListPage(OverdueBaseCondition condition,int page ,int pagesize){
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        condition.setRoleId(CurrentThreadContext.getCurrentRoleId());
        if(StringUtils.isEmpty(condition.getTableNm())){
            condition.setTableNm(null);
        }
        Pager pager = this.overdueService.getOverdueCustomerListPage(condition, page, pagesize);
        List<OverdueCstVO> resultList = (List<OverdueCstVO>) pager.getResultList();
        if(null !=resultList){
            //查詢用戶风险等级
            for (OverdueCstVO overdueCstVO : resultList) {
                if(null != overdueCstVO.getCstId()){
                    try{
                        CCardResult cRiskLevel = riskLevelService.getCRiskLevel(overdueCstVO.getCstId());
                        overdueCstVO.setFinalRiskLevel(cRiskLevel.getFinalRiskLevel());
                    }catch (Exception e){
                        logger.error("查询客户C卡异常 cstId={}",overdueCstVO.getCstId());
                    }
                }else{
                    //TODO 客户id为空
                    logger.error("查询客户C卡异常 客户Id为空");
                }
            }
        }
        ListPageVO<OverdueCstVO> overdueCstVOListPageVO = new ListPageVO<OverdueCstVO>(resultList, pager.getTotalCount());
        return overdueCstVOListPageVO;
    }



    /**
     * 获取某用户的逾期合同
     * @param cstId
     * @return
     */
    @RequestMapping("/overdueContractList.do")
    @ResponseBody
    public ListPageVO overdueContractList(@RequestParam(required = true) Long cstId, OverdueContractQueryCondition condition,String myTask){
        ListPageVO<OverdueContractVO> res = null;
        try {
        if(StringUtils.isBlank(myTask)){
            condition.setUsrId(CurrentThreadContext.getCurrentUserId());
            condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        }else{
            //我的任务不使用 除了客户ID之外的其他过滤条件
            condition = new OverdueContractQueryCondition();
            condition.setCstId(cstId);
        }
        if(StringUtils.isNotBlank(condition.getCstMgrNm())) {
        	condition.setCstMgrName(null);
        }
        List<OverdueContractVO> overdueContractList = overdueService.getOverdueContractList(condition);
            res= new ListPageVO<>(overdueContractList,overdueContractList.size());
        }catch (Exception e){
            BaseLogUtils.error(logger,"overdueContractList",e.getMessage());
            throw e;
        }
        return res;
    }

    /**
     * 获取逾期支付表
     * @return
     */
    @RequestMapping("/overduePaySchList.do")
    @ResponseBody
    public ListPageVO overduePaySchList(@RequestParam(required = true) Long prjId, OverduePaySchQueryCondition condition,String myTask){
        ListPageVO<OverduePaySchVO> res = null;
        try {
            if(StringUtils.isBlank(myTask)){
                condition.setUsrId(CurrentThreadContext.getCurrentUserId());
                condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
            }else{
                // 我的任务 可以全看
                condition = new OverduePaySchQueryCondition();
                condition.setPrjId(prjId);
            }
            List<OverduePaySchVO> overduePaySchList = overdueService.getOverduePaySchList(condition);
            res = new ListPageVO<>(overduePaySchList,overduePaySchList.size());
        }catch (Exception e){
            BaseLogUtils.error(logger,"overduePaySchList",e.getMessage());
            throw  e;
        }
        return res;
    }

    /**
     * 点击还款明细
     * 查询客户资金资金列表
     * @param model
     * @param cstId
     * @param cstNm
     * @return
     */
    @RequestMapping("/toCstCapFundListPage.do")
    public ModelAndView toCstCapFundListPage(ModelAndView model,
                                             @RequestParam String cstId,
                                             @RequestParam String cstNm){
        model.setViewName("/risknew/ovdueCollect/capRepaymentDtlList");
        model.addObject("cstId",cstId);
        model.addObject("cstNm",cstNm);
        return model;
    }

    /**
     *
     * 客户资金列表
     * @param cstId
     * @return
     */
    @RequestMapping("/initCstCapFundList.do")
    @ResponseBody
    public ListPageVO initCstCapFundList(Long cstId,int page ,int pagesize){
        Pager pager = new Pager();
        pager.setCurrentPage(page);
        pager.setEveryPage(pagesize);
        OverdueCapFundQueryCondition qc = new OverdueCapFundQueryCondition();
        qc.setCstId(cstId);
        pager.setCondition(qc);
        pager = overdueService.cstOverdueCapFundListPage(pager);
        List<OverdueCapFundVO> overdueCapFundVOS = (List<OverdueCapFundVO>) pager.getResultList();

        ListPageVO<OverdueCapFundVO> res = new ListPageVO<>(overdueCapFundVOS,pager.getTotalCount());
        return res;
    }

    /**
     *
     * 点击应收金额
     * 查看逾期支付表详情
     * 三个参数至少会有一个，客户应收金额cstid,项目应收金额prjId,支付表应收金额paySchId
     * @param model
     * @param cstId
     * @param prjId
     * @param paySchId
     * @return
     */
    @RequestMapping("/toOverduePaySchDList.do")
    public ModelAndView toOverduePaySchDList(ModelAndView model ,Long cstId,Long prjId,Long paySchId,Long arAmt,Long ovdAmt,Long fineAmt){
        model.setViewName("/risknew/ovdueCollect/overduePaySchDS01");
        model.addObject("cstId",cstId);
        model.addObject("prjId",prjId);
        model.addObject("paySchId",paySchId);
        model.addObject("arAmt",MoneyConvert.fen2Yuan(arAmt));
        model.addObject("ovdAmt",MoneyConvert.fen2Yuan(ovdAmt));
        model.addObject("fineAmt",MoneyConvert.fen2Yuan(fineAmt));

        return model;
    }

    /**
     *  应收金额 initList
     *  初始化逾期支付表详情数据
     * @param cstId 客户id 点击客户应付金额有这个参数
     * @param prjId 项目id 点击项目应付金额有这个参数
     * @param paySchId 支付表id 点击支付表应付金额有这个参数
     * @return
     */
    @RequestMapping("/initOverduePaySchDList.do")
    @ResponseBody
    public Object initOverduePaySchDList(Long cstId,Long prjId,Long paySchId,PaySchDQueryCondition condition,
                                         @RequestParam int page,
                                         @RequestParam int pagesize){
        Pager pager = new Pager ();
        pager.setEveryPage(pagesize);
        pager.setCurrentPage(page);
        pager.setCondition(condition);
        pager = this.overdueService.selectOverduePaySchDS01ListPage(pager);
        List<OverduePaySchDVO> resultList = (List<OverduePaySchDVO>) pager.getResultList();
        ListPageVO<OverduePaySchDVO> res = new ListPageVO<>(resultList,pager.getTotalCount());
        return res;
    }

    /**
     * 车辆详情
     * @param condition : paySchId 支付表ID
     * @return
     */
    @RequestMapping("/carDetail.do")
    @ResponseBody
    public ModelAndView carDetail(ModelAndView model ,PrjPrdDtlQueryCondition condition){
        // view
        model.setViewName("/risknew/ovdueCollect/carDetail");
        // 项目产品DTL
        PrjPrdDtlVO prjPrdDtlVO = dtlService.selectOneByCondition(condition);
        model.addObject("prjPrdDtl",prjPrdDtlVO);
        // 项目产品EXT
        if(prjPrdDtlVO != null){
            PrjPrdDtlExtDTO prjPrdDtlExtDTO = dtlExtApiService.selectById(prjPrdDtlVO.getId());
            model.addObject("veh",prjPrdDtlExtDTO);
        }
        // 合格证
        if(prjPrdDtlVO != null){
            PrjPrdVehInfoVO prjPrdVehInfoVO = vehInfoService.selectById(prjPrdDtlVO.getActPrdId());
            model.addObject("veh",prjPrdVehInfoVO);
        }
        // 上牌
        if(prjPrdDtlVO!=null){
            PrjPrdLicInfoVO prjPrdLicInfoVO = licInfoService.selectById(prjPrdDtlVO.getId());
            model.addObject("lic",prjPrdLicInfoVO);
        }
        // 抵押
        if(prjPrdDtlVO!=null){
            PrjPrdMtgVO prjPrdMtgVO = mtgService.selectById(prjPrdDtlVO.getId());
            model.addObject("mtg",prjPrdMtgVO);
        }
        return model;
    }
    
    /**
    *
    * 点击查看结清价按钮
    * @param model
    * @param paySchId 支付表ID
    * @param arAmt 应收金额
    * @param ovdAmt 逾期金额
    * @param fineAmt 罚息金额
    * @param tableNm 支付表名称
    * @return
    */
   @RequestMapping("/toOverdueClearingPrice.do")
   public ModelAndView toOverdueClearingPrice(ModelAndView model ,Long paySchId,Long arAmt,Long ovdAmt,Long fineAmt,String tableNm,String overdueDay){
       model.setViewName("/risknew/ovdueCollect/clearingPrice");
       model.addObject("paySchId",paySchId);
       // 未来本金
       double futureCapAmt = 0d;
       if ("PRJ_PRD_PAY_SCH_M".equals(tableNm)) {
           PrjPrdPaySchDQueryCondition qc = new PrjPrdPaySchDQueryCondition();
           qc.setFeeTypCd(CapitalConstant.CODE_FEE_TYP_CD_S03);
           qc.setPaySchId(paySchId);
           qc.setPayDtMin(DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DDHHMMSS));
           List<PrjPrdPaySchDVO> list = prjPrdPaySchDService.searchList(qc);
           if (CollectionUtils.isNotEmpty(list)) {
               for (PrjPrdPaySchDVO vo : list) {
                   futureCapAmt += vo.getArAmt();
               }
           }
       } else if ("MCR_BILL_M".equals(tableNm)) {
           McrBillDQC qc = new McrBillDQC();
           qc.setBillId(paySchId);
           List<McrBillDVO> list = mcrBillDService.searchList(qc);
           Date date = new Date();
           if (CollectionUtils.isNotEmpty(list)) {
               for (McrBillDVO vo : list) {
                   if (vo.getPayDt().after(date)) {
                       double temp = vo.getCapAmt() - vo.getPaidCapAmt();
                       futureCapAmt += temp;
                   }
               }
           }
       } else if ("INS_PAY_INFO".equals(tableNm)) {
           InsPayDetailIns03QC qc = new InsPayDetailIns03QC();
           qc.setInsPayInfoId(paySchId);
           List<InsPayDetailIns03DTO> list = insPayInfoService.searchPay03List(qc);
           Date date = new Date();
           if (CollectionUtils.isNotEmpty(list)) {
               for (InsPayDetailIns03DTO dto : list) {
                   if (dto.getRepaymentDt().after(date)) {
                       futureCapAmt += dto.getArAmt();
                   }
               }
           }
       }
       model.addObject("futureCapAmt", futureCapAmt);
       if(StringUtils.isEmpty(arAmt)){
    	   model.addObject("arAmt",0L);
       }else{
    	   model.addObject("arAmt",arAmt);
       }
       if(StringUtils.isEmpty(ovdAmt)){
    	   model.addObject("ovdAmt",0L);
       }else{
    	   model.addObject("ovdAmt",ovdAmt);
       }
	   if(StringUtils.isEmpty(fineAmt)){
		   model.addObject("fineAmt",0L); 
	   }else{
		   model.addObject("fineAmt",fineAmt);   
	   }
	   model.addObject("tableNm",tableNm);
	   model.addObject("overdueDay",overdueDay);
       return model;
   }
   
   /**
    *  结清价 initList
    *  初始化逾期支付表详情数据
    * @param paySchId 支付表id 
    * @return
    */
   @SuppressWarnings("unchecked")
   @RequestMapping("/initOverdueClearingPriceList.do")
   @ResponseBody
   public Object initOverdueClearingPriceList(Long paySchId,String tableNm,
                                        @RequestParam int page,
                                        @RequestParam int pagesize){
	   PaySchDQueryCondition condition = new PaySchDQueryCondition();
	   condition.setPaySchId(paySchId);
       Pager pager = new Pager ();
       pager.setEveryPage(pagesize);
       pager.setCurrentPage(page);
       pager.setCondition(condition);
       pager = this.overdueService.selectOverduePaySchDS01AndFEEListPage(pager,tableNm);
       List<OverduePaySchDVO> resultList = (List<OverduePaySchDVO>) pager.getResultList();
       ListPageVO<OverduePaySchDVO> res = new ListPageVO<>(resultList,pager.getTotalCount());
       return res;
   }
   /**
    * 点击实付明细按钮
    * @param model
    * @param payDetailId 明细ID
    * @return
    */
   @RequestMapping("/toOverdueCapFundVfDtlPage.do")
   public ModelAndView toOverdueCapFundVfDtlPage(ModelAndView model ,Long payDetailId,Long paySchId,Long payPd){
       model.setViewName("/risknew/ovdueCollect/overDueCapFundVfDtl");
       model.addObject("payDetailId",payDetailId);
       model.addObject("paySchId",paySchId);
       model.addObject("payPd",payPd);
       return model;
   }
   @SuppressWarnings("unchecked")
   @RequestMapping("/initOverdueCapFundVfDtlList.do")
   @ResponseBody
   public Object initOverdueCapFundVfDtlList(Long payDetailId,Long paySchId,Long payPd,
                                        @RequestParam int page,
                                        @RequestParam int pagesize){
	   if(StringUtils.isNotEmpty(payDetailId)){
		   OverdueCapFundVfDtlQueryCondition condition= new OverdueCapFundVfDtlQueryCondition();
		   if(!payPd.equals(0L)){			   
			   condition.setPaySchId(paySchId);
			   condition.setPayPd(payPd);
		   }else{
			   condition.setPayDetailId(payDetailId);			   
		   }
		   Pager pager = new Pager ();
	       pager.setEveryPage(pagesize);
	       pager.setCurrentPage(page);
	       pager.setCondition(condition);
	       pager = this.overdueService.selectOverdueFundVfDtlListPage(pager);
	       List<OverdueCapFundVfDtlVO> resultList = (List<OverdueCapFundVfDtlVO>) pager.getResultList();
	       ListPageVO<OverdueCapFundVfDtlVO> res = new ListPageVO<>(resultList,pager.getTotalCount());
	       return res;
	   }else{
		   ListPageVO<OverdueCapFundVfDtlVO> res = new ListPageVO<>(null,0);
		   return res;
	   }
   }
   
   @RequestMapping("/getfinalPayAmt.do")
   @ResponseBody
   public DataResultVO getfinalPayAmt(Long paySchId,String tableNm,Long ovdAmt,Long fineAmt){
	   DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "查询成功");
	   try{
//		   Map<String, Object> finalPay = this.overdueService.getfinalPayAmt(paySchId,tableNm,ovdAmt,fineAmt);
		   PrjPrdPaySchMVO pay =this.prjPrdPaySchMService.selectById(paySchId);
		   PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(pay.getPrjId());
		   pay.setBuOrgCd(prjBscInfoVO.getBuOrgCd());
		   result.setData(pay);
	   }catch (Exception e) {
		   result.setSuccess(BaseConstant.IS_YESNO_NO);
           result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
           BaseLogUtils.error(logger, "getfinalPayAmt", "查询提前结清价失败,系统错误.paySchId:" + paySchId + ".ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
	   }  
	   return result;
   }

    /**
     * 逾期催收页面  导出excel
     * @return
     */
   @RequestMapping("/exportOverdueExcel.do")
   @ResponseBody
   public DataResultVO exportOverdueExcel(OverdueBaseCondition condition ){
       BaseLogUtils.info(logger,"exportOverdueExcel","逾期催收新-导出,操作人："+CurrentThreadContext.getCurrentUserId());
       condition.setUsrId(CurrentThreadContext.getCurrentUserId());
       condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
       // 导出完成后返回一个地址
       return this.overdueService.exportOverdueExcel(condition);
   }

    /**
     * 到应收款计算器页面
     * @param model
     * @param arAmt
     * @param ovdAmt
     * @param fineAmt
     * @param ovdDay
     * @return
     */
    @RequestMapping("toCalculator.do")
    public ModelAndView toCalculator(ModelAndView model,Long arAmt,Long ovdAmt,Long fineAmt ,Long ovdDay,Long cstId){
       model.setViewName("/risknew/ovdueCollect/calculator");
       model.addObject("arAmt",arAmt);
       model.addObject("ovdAmt",ovdAmt);
       model.addObject("fineAmt",fineAmt);
       model.addObject("ovdDay",ovdDay);
       model.addObject("cstId",cstId);
       return model;
    }

    /**
     * 计算应收款
     * @return
     */
    @RequestMapping("doCal.do")
    @ResponseBody
    public DataResultVO doCal(String createDate,Long cstId){
        DataResultVO resultVO = new DataResultVO();
        try{
            OverdueCstDTO res = overdueCalculatorApiService.calculate(DateUtils.formatStringToDate(createDate, DateUtils.YYYY_MM_DD), cstId);
            if(res != null){
                resultVO.setSuccess(1);
                resultVO.setData(res);
                resultVO.setInfo("计算完毕");
            }
        }catch (Exception e){
            BaseLogUtils.info(logger,"doCal","应收款计算失败");
            resultVO.setSuccess(0);
            resultVO.setData(null);
            resultVO.setInfo("计算失败。没有获取到逾期信息（可能是选择的日期不存在逾期）。");
        }
        return resultVO;
    }

    /**
     * 总数
     * @return
     */
    @RequestMapping("sum.do")
    @ResponseBody
    public OverdueCstVO sum(OverdueBaseCondition condition){
        // 数据权限
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        String insCode = condition.getInsCode();
        if(StringUtils.isNotBlank(insCode)){
            List<String> insCodeList = Arrays.asList(insCode.split(";"));
            condition.setInsCode(null);
            condition.setInsCodeList(insCodeList);
        }
        String buOrgCd = condition.getBuOrgCd();
        if(StringUtils.isNotBlank(buOrgCd)){
            List<String> buOrgCdList = Arrays.asList(buOrgCd.split(";"));
            condition.setBuOrgCd(null);
            condition.setBuOrgCdList(buOrgCdList);
        }
        return this.overdueService.getSum(condition);
    }

     /**
      * @Author huangkailun
      * @Date 15:08 2019-06-13
      * @Description 贷后项目资料补充流程附加页面
      * @Param
      * @return
      */
    @RequestMapping("/toFileSupplyActvitiPage.do")
    @ResponseBody
    public ModelAndView toFileSupplyActvitiPage(HttpServletRequest request, HttpServletResponse response) {
        // 补充资料上传记录id
        String fsId = request.getParameter("fsId");
        // 节点flag
        String flag = request.getParameter("flag");
        BaseLogUtils.info(logger, "toFileSupplyActvitiPage", "贷后补充资料审核上传记录id--->" + fsId);
        ModelAndView mav = new ModelAndView("/risknew/ovdueCollect/fileSupplyActivitiPage");
        if (StringUtils.isEmpty(fsId)) {
            throw new BaseException("无法获取贷后资料上传id");
        }
        // 获取当前贷后资料上传记录
        RskUlFileLogVO rskUlFileLogVO = this.iRskUlFileLogService.selectById(Long.parseLong(fsId));
        if (null != rskUlFileLogVO) {
            Long prjId = rskUlFileLogVO.getPrjId();
            mav.addObject("prjId", prjId);
            mav.addObject("fsId", fsId);
            mav.addObject("flag", flag);
            mav.addObject("cfgCd", PrjFileInfoConstant.CODE_UL_PRJ_FILE_CFG_CD);
            if (StringUtils.isNotEmpty(prjId)) {
                PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjId));
                if (null != prjBscInfoVO) {
                    mav.addObject("cstId", prjBscInfoVO.getCstId());
                    mav.addObject("cstMgrOrgCd", prjBscInfoVO.getCstMgrOrgCd());//客户经理组织架构代码
                    mav.addObject("prjTypCd", prjBscInfoVO.getPrjTypCd());//项目类型
                    mav.addObject("insCode", StringUtils.isNotEmpty(prjBscInfoVO.getInsCode()) ? prjBscInfoVO.getInsCode() : "");//机构编码
                }
            }
            if (null != rskUlFileLogVO) {
                mav.addObject("UlRem", rskUlFileLogVO.getUlRem());
            }
        }
        return mav;
    }

    /**
     * 在呈报人再次提交节点修改补充说明
     * @param request
     * @return
     * @throws BaseException
     */
    @RequestMapping("/updateRskUlFileLog.do")
    @ResponseBody
    public Object updateRskUlFileLog(HttpServletRequest request) throws BaseException {
        DataResultVO resultVO = new DataResultVO();
        resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
        // 文件补充记录id
        String fsId = request.getParameter("fsId");
        // 补充说明
        String ulRem = request.getParameter("ulRem");
        try {
            RskUlFileLogVO vo = new RskUlFileLogVO();
            if (StringUtils.isNotEmpty(fsId)) {
                vo.setId(Long.parseLong(fsId));
            }
            vo.setUlRem(ulRem);
            boolean success = this.iRskUlFileLogService.modify(vo);
            if (success == true) {
                resultVO.setSuccess(BaseConstant.IS_YESNO_YES);
            } else {
                throw new BaseException("更新补充记录失败：fsId===" + fsId);
            }
        } catch (Exception e) {
            BaseLogUtils.error(logger, "updateRskUlFileLog", "更新补充记录失败：fsId===" + fsId, e);
        }
        return resultVO;
    }

    /**
     * 获取当前项目的逾期信息
     * @param prjId
     * @return
     */
    @RequestMapping("/getPrjAndContractList.do")
    @ResponseBody
    public Object getPrjAndContractList (@RequestParam Long prjId) {
        PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(prjId);
        OverdueContractQueryCondition condition = new OverdueContractQueryCondition();
        ListPageVO<OverdueContractVO> res = null;
        try {
            condition.setPrjId(prjId);
            condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
            if(StringUtils.isNotBlank(condition.getCstMgrNm())) {
                condition.setCstMgrName(null);
            }
            List<OverdueContractVO> overdueContractList = overdueService.getOverdueContractList(condition);
            if (CollectionUtils.isEmpty(overdueContractList)) {
                OverdueContractVO overdueContractVO = new OverdueContractVO();
                overdueContractVO.setBuOrgCd(prjBscInfoVO.getBuOrgCd());
                overdueContractVO.setLsCntNo(prjBscInfoVO.getLsCntNo());
                overdueContractVO.setCstNm(prjBscInfoVO.getCstNm());
                overdueContractList.add(overdueContractVO);
            }
            res= new ListPageVO<>(overdueContractList,overdueContractList.size());
        } catch (Exception e) {
            BaseLogUtils.error(logger,"getPrjAndContractList",e.getMessage());
            throw e;
        }
        return res;
    }

    /**
     * 获取贷后资料补充流程的流程附加页面的逾期支付表
     * @return
     */
    @RequestMapping("/getOverduePaySchList4FileSup.do")
    @ResponseBody
    public ListPageVO getOverduePaySchList4FileSup(@RequestParam(required = true) Long prjId, OverduePaySchQueryCondition condition){
        ListPageVO<OverduePaySchVO> res = null;
        try {
            condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
            if (StringUtils.isNotEmpty(prjId)) {
                condition.setPrjId(prjId);
            }
            List<OverduePaySchVO> overduePaySchList = overdueService.getOverduePaySchList(condition);
            res = new ListPageVO<>(overduePaySchList,overduePaySchList.size());
        }catch (Exception e){
            BaseLogUtils.error(logger,"overduePaySchList",e.getMessage());
            throw  e;
        }
        return res;
    }

    /**
     * 总数
     * @return
     */
    @RequestMapping("getSum4FileSup.do")
    @ResponseBody
    public OverdueCstVO getSum4FileSup(OverdueBaseCondition condition){
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        return this.overdueService.getSum(condition);
    }

}
